package ru.urfc.portal.security;

import java.util.Set;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;

@Stateless
public class PortalUserManager {
	
	@PersistenceContext(name = "webspace", unitName = "webspace")
	private EntityManager entityManager;
	
	public String emailFromId(final String userid) {
		if (userid == null) {
			return null;
		}
		final PortalUser portalUser = entityManager.find(PortalUser.class, Long.parseLong(userid));
		return portalUser.getEmailaddress();
	}
	
	public void grantClientAdminRoles(String email) {
		PortalUser user = getUserByEmail(email);
		PortalRole roleClientAdmin = getRoleByName("Администратор Клиента");
		PortalRole roleClientUser = getRoleByName("Представитель Клиента");
		final Set<PortalRole> roles = user.getRoles();
		roles.add(roleClientAdmin);
		roles.add(roleClientUser);
	}
	
	public PortalRole getRoleByName(String name) {
		final CriteriaQuery<PortalRole> q = entityManager.getCriteriaBuilder().createQuery(
				PortalRole.class);
		return entityManager.createQuery(
				q.where(entityManager.getCriteriaBuilder().equal(
						q.from(PortalRole.class).get("name"), name))).getSingleResult();
	}
	
	public PortalUser getUserByEmail(String email) {
		final CriteriaQuery<PortalUser> q = entityManager.getCriteriaBuilder().createQuery(
				PortalUser.class);
		return entityManager.createQuery(
				q.where(entityManager.getCriteriaBuilder().equal(
						q.from(PortalUser.class).get("emailaddress"), email))).getSingleResult();
	}
	
}
